package controllers

import (
	"baokaobang/datasourse"
	"baokaobang/logic"
	"baokaobang/models"
	"baokaobang/utils"
	"baokaobang/wechat"
	"fmt"
	"html/template"
	"strconv"
	"strings"
	"time"

	"github.com/go-xorm/xorm"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"github.com/kataras/iris/v12/sessions"
	rc "github.com/rongcloud/server-sdk-go/v3/sdk"
)

type NoLogin struct {
	Ctx iris.Context
}

func (c *NoLogin) GetTest() interface{} {
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	college := new(models.CollegeObj)
	_, err = db.Table(new(models.College)).Alias("c").
		Join("INNER", []string{"university", "u"}, "c.university_id = u.id").
		Where("c.id = ?", 1).
		Get(college)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("操作失败：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "操作成功", college)
}

// 判断用户是否已经登录
func (c *NoLogin) PostIslogin() interface{} {
	channel := c.Ctx.PostValueDefault("channel", "")
	if len(channel) <= 0 {
		return utils.CommonRes(1000, "请提供渠道", "")
	}

	var userId int64
	session := sessions.Get(c.Ctx)
	userId, _ = session.GetInt64(fmt.Sprintf("%sUserId", channel))
	if userId <= 0 {
		return utils.CommonRes(20003, "您还没有登录", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	user := new(models.User)
	ok, err := db.ID(userId).Get(user)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("根据id查询用户出错：%s", err.Error()), "")
	}
	if !ok {
		return utils.CommonRes(1000, "用户信息异常", "")
	}

	res := logic.GetUserExtraInfo(db, user)
	if res["code"] != 20000 {
		return res
	}

	data := map[string]interface{}{
		"userInfo": user,
	}

	return utils.CommonRes(20000, "已登录", data)
}

// 小程序登录
func (c *NoLogin) PostMini() interface{} {
	code := c.Ctx.PostValueDefault("code", "")
	encodeData := c.Ctx.PostValueDefault("encodeData", "")
	iv := c.Ctx.PostValueDefault("iv", "")

	if len(code) <= 0 {
		return utils.CommonRes(20002, "缺少临时登录凭证code", "")
	}

	session := sessions.Get(c.Ctx)

	var err error
	var ok bool
	var miniLoginRes *wechat.MiniLoginRes
	var wxUserInfo *wechat.WxUserInfo

	miniLogin := wechat.NewMiniLogin(code)
	miniLoginRes, err = miniLogin.Login()
	if err != nil {
		return utils.CommonRes(20002, fmt.Sprintf("登录失败：%s", err.Error()), "")
	}
	if miniLoginRes.Errcode != 0 {
		return utils.CommonRes(20002, fmt.Sprintf("登录异常：%s", miniLoginRes.Errmsg), "")
	}

	wxUserDataCrypt := wechat.NewWXUserDataCrypt(miniLoginRes.SessionKey, iv, encodeData)
	wxUserInfo, err = wxUserDataCrypt.Decrypt()
	if err != nil {
		return utils.CommonRes(20010, fmt.Sprintf("解析用户信息失败：%s", err.Error()), "")
	}
	if len(wxUserInfo.UnionID) <= 0 {
		return utils.CommonRes(20002, "登录失败，用户unionid异常", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	user := new(models.User)
	ok, err = db.Where("`unionid` = ?", wxUserInfo.UnionID).Get(user)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("根据unionid查询用户出错：%s", err.Error()), "")
	}

	session.Set("miniOpenid", wxUserInfo.OpenID)
	session.Set("unionid", wxUserInfo.UnionID)
	session.Set("avatarUrl", wxUserInfo.AvatarURL)
	session.Set("nickName", wxUserInfo.NickName)
	session.Set("gender", wxUserInfo.Gender)

	sessionId := session.ID()
	data := map[string]interface{}{
		"sessionId": sessionId,
	}

	if !ok {
		return utils.CommonRes(20002, "用户未注册", data)
	}
	if user.UserType <= 0 {
		return utils.CommonRes(20002, "用户未注册", data)
	}

	updateData := map[string]interface{}{
		"avatar":    wxUserInfo.AvatarURL,
		"nick_name": wxUserInfo.NickName,
		"gender":    wxUserInfo.Gender,
		"token":     sessionId,
	}
	db.Table(new(models.User)).ID(user.Id).Update(updateData)

	res := logic.GetUserExtraInfo(db, user)
	if res["code"] != 20000 {
		return res
	}

	data["userInfo"] = user
	session.Set("miniUserId", user.Id)

	return utils.CommonRes(20000, "成功登录", data)
}

// APP微信登录
func (c *NoLogin) PostWechat() interface{} {
	code := c.Ctx.PostValueDefault("code", "")
	channel := c.Ctx.PostValueDefault("channel", "")

	if len(code) <= 0 {
		return utils.CommonRes(1000, "登录失败，缺少临时登录凭证code", "")
	}
	if len(channel) <= 0 {
		return utils.CommonRes(1000, "请提供登录渠道", "")
	}

	session := sessions.Get(c.Ctx)

	var err error
	var ok bool
	var accessTokenRes *wechat.AppAccessTokenRes

	appAccessToken := wechat.NewAppAccessToken(code)
	accessTokenRes, err = appAccessToken.Get()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("登录失败，无法获取access_token：%s", err.Error()), "")
	}
	if accessTokenRes.Errcode != 0 {
		return utils.CommonRes(1000, fmt.Sprintf("登录失败，%s", accessTokenRes.Errmsg), "")
	}

	var appUserInfoRes *wechat.AppUserInfoRes

	appUserInfo := wechat.NewAppUserInfo(accessTokenRes.AccessToken, accessTokenRes.Openid)
	appUserInfoRes, err = appUserInfo.Get()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("登录失败，无法获取用户微信信息：%s", err.Error()), "")
	}
	if appUserInfoRes.Errcode != 0 {
		return utils.CommonRes(1000, fmt.Sprintf("登录失败，%s", appUserInfoRes.Errmsg), "")
	}
	if len(appUserInfoRes.Unionid) <= 0 {
		return utils.CommonRes(1000, "登录失败，用户unionid异常", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("登录失败，无法连接数据库：%s", err.Error()), "")
	}

	user := new(models.User)
	ok, _ = db.Where("`unionid` = ?", appUserInfoRes.Unionid).Get(user)

	session.Set("appOpenid", appUserInfoRes.Openid)
	session.Set("unionid", appUserInfoRes.Unionid)
	session.Set("avatarUrl", appUserInfoRes.Headimgurl)
	session.Set("nickName", appUserInfoRes.Nickname)
	session.Set("gender", appUserInfoRes.Sex)

	sessionId := session.ID()

	data := map[string]interface{}{
		"sessionId": sessionId,
	}

	if !ok {
		return utils.CommonRes(20002, "用户未注册", data)
	}
	if user.UserType <= 0 {
		return utils.CommonRes(20002, "用户未注册", data)
	}

	updateData := map[string]interface{}{
		"avatar":    appUserInfoRes.Headimgurl,
		"nick_name": appUserInfoRes.Nickname,
		"gender":    appUserInfoRes.Sex,
		"token":     sessionId,
	}
	db.Table(new(models.User)).ID(user.Id).Update(updateData)

	res := logic.GetUserExtraInfo(db, user)
	if res["code"] != 20000 {
		return res
	}

	data["userInfo"] = user
	session.Set(fmt.Sprintf("%sUserId", channel), user.Id)

	return utils.CommonRes(20000, "登录成功", data)
}

// 手机号+验证码登录
func (c *NoLogin) PostCodelogin() interface{} {
	phone := strings.TrimSpace(c.Ctx.PostValueDefault("phone", ""))
	code := strings.TrimSpace(c.Ctx.PostValueDefault("code", ""))
	channel := c.Ctx.PostValueDefault("channel", "")

	session := sessions.Get(c.Ctx)

	if !strings.EqualFold(phone, "66668888222") { // 66668888222用于测试审核

		if len(channel) <= 0 {
			return utils.CommonRes(1000, "请提供登录渠道", "")
		}
		if len(phone) <= 0 {
			return utils.CommonRes(1000, "请输入手机号", "")
		}
		if len(code) <= 0 {
			return utils.CommonRes(1000, "请输入验证码", "")
		}

		db, err := datasourse.NewMasterOrm()
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("登录失败，无法连接数据库：%s", err.Error()), "")
		}

		user := new(models.User)
		ok, err := db.Where("`phone` = ?", phone).Get(user)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("登录失败：%s", err.Error()), "")
		}
		if !ok {
			return utils.CommonRes(1000, "登录失败，该手机号尚未注册", "")
		}

		verifyCode := utils.NewVerifyCode(phone, code)
		ok, msg := verifyCode.Check()
		if !ok {
			return utils.CommonRes(1000, msg, "")
		}

		res := logic.GetUserExtraInfo(db, user)
		if res["code"] != 20000 {
			return res
		}

		session.Set(fmt.Sprintf("%sUserId", channel), user.Id)
		sessionId := session.ID()

		updateData := map[string]interface{}{
			"token": sessionId,
		}
		db.Table(new(models.User)).ID(user.Id).Update(updateData)

		data := map[string]interface{}{
			"sessionId": sessionId,
			"userInfo":  user,
		}

		return utils.CommonRes(20000, "登录成功", data)

	} else {

		session.Set(fmt.Sprintf("%sUserId", channel), int64(1))

		return utils.CommonRes(20000, "登录成功", "")

	}

}

// 用户名+密码登录
func (c *NoLogin) PostDologin() interface{} {
	phone := strings.TrimSpace(c.Ctx.PostValueDefault("phone", ""))
	password := strings.TrimSpace(c.Ctx.PostValueDefault("password", ""))
	channel := c.Ctx.PostValueDefault("channel", "")
	// userType := c.Ctx.PostValue("type")
	session := sessions.Get(c.Ctx)

	if len(channel) <= 0 {
		return utils.CommonRes(1000, "请提供登录渠道", "")
	}
	if len(phone) <= 0 {
		return utils.CommonRes(1000, "请输入手机号", "")
	}
	if len(password) <= 0 {
		return utils.CommonRes(1000, "请输入密码", "")
	}

	// var rcToken string
	// if userType == "2" {
	// 	//创建融云对象  传入appkey、appsecret
	// 	rongCloud := rc.NewRongCloud("x18ywvqfx4c1c", "Y3Vo93Qk1cC")
	// 	if rongCloud == nil {
	// 		return utils.CommonRes(1000, fmt.Sprintf("创建融云对象失败"), "")
	// 	}

	// 	//获取userId
	// 	var userId int64
	// 	session = sessions.Get(c.Ctx)
	// 	userId, _ = session.GetInt64(fmt.Sprintf("%sUserId", channel))
	// 	userID := strconv.FormatInt(userId, 10)

	// 	//注册融云账号
	// 	//头像地址
	// 	avatarUri := "https://www.zhaobanzhilian.com"
	// 	rcToken, err := rongCloud.UserRegister(userID, name, avatarUri)
	// 	if err != nil {
	// 		return utils.CommonRes(1000, fmt.Sprintf("融云账号注册失败: %s", err.Error()), "")
	// 	}

	// 	//获取大学名字
	// 	ok, err = sess.Where("`code` = ?", collegeCode).Get(college)
	// 	if err != nil {
	// 		return utils.CommonRes(1000, fmt.Sprintf("根据招生代码查询院校出错：%s", err.Error()), "")
	// 	}

	// 	groupName := college.Name

	// 	//创建群组
	// 	err = rongCloud.GroupCreate(collegeCode, groupName, []string{userID})
	// 	if err != nil {
	// 		return utils.CommonRes(1000, fmt.Sprintf("创建群组失败"), err)
	// 	}
	// }

	// session := sessions.Get(c.Ctx)

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("登录失败，无法连接数据库：%s", err.Error()), "")
	}

	user := new(models.User)
	ok, err := db.Where("`phone` = ?", phone).Get(user)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("登录失败：%s", err.Error()), "")
	}
	if !ok {
		return utils.CommonRes(1000, "登录失败，该手机号尚未注册", "")
	}

	if !strings.EqualFold(user.Password, utils.PasswordEncode(password)) {
		return utils.CommonRes(1000, "登录失败，密码输入不正确", "")
	}

	res := logic.GetUserExtraInfo(db, user)
	if res["code"] != 20000 {
		return res
	}

	session.Set(fmt.Sprintf("%sUserId", channel), user.Id)
	sessionId := session.ID()

	userID := strconv.FormatInt(user.Id, 10)

	token, err := utils.GenerateToken(user.Name, password, userID)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("生成token有误: %s", err.Error()), "")
	}

	updateData := map[string]interface{}{
		"token": sessionId,
	}
	db.Table(new(models.User)).ID(user.Id).Update(updateData)

	data := map[string]interface{}{
		"sessionId": sessionId,
		"userInfo":  user,
		"token":     token,
		// "rcToken":   rcToken,
	}

	return utils.CommonRes(20000, "登录成功", data)
}

// 用户注册
func (c *NoLogin) PostRegister() interface{} {
	session := sessions.Get(c.Ctx)
	channel := c.Ctx.PostValueDefault("channel", "")
	phone := strings.TrimSpace(c.Ctx.PostValueDefault("phone", ""))

	var rcToken rc.User
	// var token string
	if !strings.EqualFold(phone, "66668888222") { // 66668888222用于测试审核

		parentId := utils.Atoi64(c.Ctx.PostValueDefault("parentId", "0"))
		highSchoolId := c.Ctx.PostValueDefault("highSchoolId", "")
		highSchoolClassId := c.Ctx.PostValueDefault("highSchoolClassId", "")
		collegeCode := c.Ctx.PostValueDefault("collegeCode", "")
		name := strings.TrimSpace(c.Ctx.PostValueDefault("name", ""))
		code := strings.TrimSpace(c.Ctx.PostValueDefault("code", ""))
		userType := c.Ctx.PostValueDefault("type", "")
		idcard := strings.TrimSpace(c.Ctx.PostValueDefault("idcard", ""))
		password := strings.TrimSpace(c.Ctx.PostValueDefault("password", ""))
		confirmPassword := strings.TrimSpace(c.Ctx.PostValueDefault("confirmPassword", ""))
		subject := utils.Atoi(c.Ctx.PostValueDefault("subject", "0"))
		regCode := strings.TrimSpace(c.Ctx.PostValueDefault("regCode", ""))
		inviteCode := strings.TrimSpace(c.Ctx.PostValueDefault("inviteCode", ""))
		address := c.Ctx.PostValue("area")

		nickName := session.GetString("nickName")
		avatar := session.GetString("avatarUrl")
		gender := session.GetString("gender")
		appOpenid := session.GetString("appOpenid")
		miniOpenid := session.GetString("miniOpenid")
		unionid := session.GetString("unionid")

		var err error
		var ok bool
		var db *xorm.Engine

		if len(name) <= 0 {
			return utils.CommonRes(1000, "请输入姓名", "")
		}
		if len(userType) <= 0 {
			return utils.CommonRes(1000, "请确定您的身份", "")
		}
		if len(phone) <= 0 {
			return utils.CommonRes(1000, "请输入手机号", "")
		}
		if len(code) <= 0 {
			return utils.CommonRes(1000, "请输入手机验证码", "")
		}
		if len(password) <= 0 {
			return utils.CommonRes(1000, "请输入登录密码", "")
		}
		if channel == "mini" {
			if !strings.EqualFold(password, confirmPassword) {
				return utils.CommonRes(1000, "两次密码输入不一致", "")
			}
		}

		if userType == "1" { // 如果是学生
			if len(idcard) <= 0 {
				return utils.CommonRes(1000, "请输入身份证号", "")
			}
			if !utils.IsIdcard(idcard) {
				return utils.CommonRes(1000, "请输入正确的身份证号", "")
			}
			if len(highSchoolId) <= 0 {
				return utils.CommonRes(1000, "请选择所在高中", "")
			}
			if len(highSchoolClassId) <= 0 {
				return utils.CommonRes(1000, "请选择所在班级", "")
			}
			if subject <= 0 {
				return utils.CommonRes(1000, "请选择科目", "")
			}
			if address == "" {
				return utils.CommonRes(1000, "请选择高中地址", "")
			}

		}

		db, err = datasourse.NewMasterOrm()
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
		}

		sess := db.NewSession()
		defer sess.Close()
		err = sess.Begin()
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("数据库事务开启失败：%s", err.Error()), "")
		}

		inviteUser := new(models.User)
		if len(inviteCode) > 0 {
			ok, err := sess.Where("`invite_code` = ?", inviteCode).Get(inviteUser)
			if err != nil {
				return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
			}
			if !ok {
				return utils.CommonRes(1000, "邀请码不存在", "")
			}
			parentId = inviteUser.Id
		}

		college := new(models.College)
		if userType == "2" {
			if len(collegeCode) <= 0 {
				return utils.CommonRes(1000, "请输入院校招生代码", "")
			}
			ok, err = sess.Where("`code` = ?", collegeCode).Get(college)
			if err != nil {
				return utils.CommonRes(1000, fmt.Sprintf("根据招生代码查询院校出错：%s", err.Error()), "")
			}
			if !ok {
				return utils.CommonRes(1000, "您输入的院校招生代码不正确", "")
			}
			if !strings.EqualFold(regCode, college.RegCode) {
				return utils.CommonRes(1000, "您输入的注册码不正确", "")
			}
			if college.RegCodeNum <= 0 {
				return utils.CommonRes(1000, "注册码使用次数已达上限", "")
			}
		}

		verifyCode := utils.NewVerifyCode(phone, code)
		ok, msg := verifyCode.Check()
		if !ok {
			return utils.CommonRes(1000, msg, "")
		}

		userInfo := new(models.User)
		ok, err = sess.Table("user").Where("`phone` = ?", phone).Get(userInfo)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("根据手机号查询用户出错：%s", err.Error()), "")
		}
		if ok {
			return utils.CommonRes(1000, "手机号已被其他会员使用", "")
		}

		if userType == "1" { // 如果是学生，则验证身份证号与姓名是否匹配
			realNameIdcard := utils.NewRealNameIdcard(idcard, name)
			realNameIdcardRes, err := realNameIdcard.Verify()
			if err != nil {
				return utils.CommonRes(1000, fmt.Sprintf("身份证与姓名验证失败：%s", err.Error()), "")
			}
			if realNameIdcardRes.ErrorCode != 0 {
				return utils.CommonRes(1000, fmt.Sprintf("身份证与姓名验证失败：%s", realNameIdcardRes.Reason), "")
			}
			if realNameIdcardRes.Result.Res == 2 {
				return utils.CommonRes(1000, "身份证号与姓名不匹配，请仔细检查", "")
			}
		}

		newInviteCode := utils.GenRandCode(8)
		ok, err = sess.Table(new(models.User)).Where("`invite_code` = ?", newInviteCode).Exist()
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("注册失败：%s", err.Error()), "")
		}
		for ok {
			newInviteCode = utils.GenRandCode(8)
			ok, _ = sess.Table(new(models.User)).Where("`invite_code` = ?", newInviteCode).Exist()
		}

		user := new(models.User)
		user.ParentId = parentId
		user.UserType = utils.Atoi(userType)
		user.HighSchoolId = utils.Atoi64(highSchoolId)
		user.HighSchoolClassId = utils.Atoi64(highSchoolClassId)
		user.CollegeId = college.Id
		user.Phone = phone
		user.Name = name
		user.Idcard = idcard
		user.NickName = nickName
		user.Avatar = avatar
		user.Gender = utils.Atoi(gender)
		user.MiniOpenid = miniOpenid
		user.AppOpenid = appOpenid
		user.Unionid = unionid
		user.Subject = subject
		user.Channel = channel
		user.Password = utils.PasswordEncode(password)
		user.InviteCode = newInviteCode

		if userType != "1" {
			user.ShortName = fmt.Sprintf("%s老师", name[0:3])
		} else {
			user.ShortName = name
		}

		_, err = sess.InsertOne(user)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("注册失败：%s", err.Error()), "")
		}

		if len(inviteCode) > 0 {
			invite := new(models.Invite)
			invite.ShareUserId = inviteUser.Id
			invite.RegUserId = user.Id
			invite.Code = inviteCode
			_, err = sess.InsertOne(invite)
			if err != nil {
				return utils.CommonRes(1000, fmt.Sprintf("注册失败：%s", err.Error()), "")
			}
		}

		collegeUpdate := map[string]interface{}{
			"reg_code_num": college.RegCodeNum - 1,
		}
		_, err = sess.Table(new(models.College)).ID(college.Id).Update(collegeUpdate)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("注册失败：%s", err.Error()), "")
		}

		sess.Commit()

		if userType == "2" {
			//创建融云对象  传入appkey、appsecret
			rongCloud := rc.NewRongCloud("x18ywvqfx4c1c", "Y3Vo93Qk1cC")
			if rongCloud == nil {
				return utils.CommonRes(1000, fmt.Sprintf("创建融云对象失败"), "")
			}

			//获取userId
			var userId int64
			session = sessions.Get(c.Ctx)
			userId, _ = session.GetInt64(fmt.Sprintf("%sUserId", channel))
			userID := strconv.FormatInt(userId, 10)

			//注册融云账号
			//头像地址
			avatarUri := "https://www.zhaobanzhilian.com"
			rcToken, err = rongCloud.UserRegister(userID, name, avatarUri)
			if err != nil {
				return utils.CommonRes(1000, fmt.Sprintf("融云账号注册失败: %s", err.Error()), "")
			}

			//获取大学名字
			ok, err = sess.Where("`code` = ?", collegeCode).Get(college)
			if err != nil {
				return utils.CommonRes(1000, fmt.Sprintf("根据招生代码查询院校出错：%s", err.Error()), "")
			}

			groupName := college.Name

			//创建群组
			err = rongCloud.GroupCreate(collegeCode, groupName, []string{userID})
			if err != nil {
				return utils.CommonRes(1000, fmt.Sprintf("创建群组失败"), err)
			}
		}

	} else {

		session.Set(fmt.Sprintf("%sUserId", channel), int64(1))

	}

	return utils.CommonRes(20000, fmt.Sprintf("注册成功"), rcToken)
}

// 发送手机验证码
func (c *NoLogin) PostSendcode() interface{} {
	ip := c.Ctx.RemoteAddr()
	phone := c.Ctx.PostValue("phone")

	if !utils.IsMobile(phone) {
		return utils.CommonRes(1000, "请输入正确的手机号", "")
	}

	//连接数据库
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	code := utils.GenRandCode(6)
	ok, _ := db.Table("verify").Where("`code` = ?", code).Exist()
	for ok {
		code = utils.GenRandCode(6)
		ok, _ = db.Table("verify").Where("`code` = ?", code).Exist()
	}

	currentTime := time.Now().Unix()
	ipVerifyRecord := new(models.Verify)
	ok, _ = db.Table(new(models.Verify)).Where("`ip` = ?", ip).Get(ipVerifyRecord)
	if ok {
		allowTime := ipVerifyRecord.SendTime.Add(1 * time.Minute).Unix()
		if currentTime < allowTime {
			return utils.CommonRes(1000, "操作过于频繁，请稍后再进行操作", "")
		}
	}

	phoneVerifyRecord := new(models.Verify)
	ok, _ = db.Table(new(models.Verify)).Where("`key` = ?", phone).Get(phoneVerifyRecord)
	if ok {
		allowTime := phoneVerifyRecord.SendTime.Add(1 * time.Minute).Unix()
		if currentTime < allowTime {
			return utils.CommonRes(1000, "操作过于频繁，请稍后再进行操作", "")
		}
		updateData := map[string]interface{}{
			"code":      code,
			"send_time": time.Now().Format("2006-01-02 15:04:05"),
			"count":     phoneVerifyRecord.Count + 1,
		}
		_, err = db.Table(new(models.Verify)).Where("`key` = ?", phone).Update(updateData)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("验证码发送失败：%s", err.Error()), "")
		}

		sendVerifyCode := utils.NewVerifyCode(phone, code)
		err = sendVerifyCode.Send()
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("验证码发送失败：%s", err.Error()), "")
		}

		return utils.CommonRes(20000, "发送成功", "")
	}

	verifyCode := new(models.Verify)
	verifyCode.Ip = ip
	verifyCode.Key = phone
	verifyCode.Code = code
	verifyCode.Count = 1
	_, err = db.InsertOne(verifyCode)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("验证码发送失败：%s", err.Error()), "")
	}

	sendVerifyCode := utils.NewVerifyCode(phone, code)
	err = sendVerifyCode.Send()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("验证码发送失败：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "发送成功", "")
}

// 获取区域列表
func (c *NoLogin) PostRegion() interface{} {
	var err error
	var db *xorm.Engine

	db, err = datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	provinceList := make([]models.Region, 0)
	err = db.Where("parent_id = ?", 0).Find(&provinceList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取区域列表：%s", err.Error()), "")
	}

	for i, province := range provinceList {
		cityList := make([]models.Region, 0)
		err = db.Where("parent_id = ?", province.Id).Find(&cityList)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("无法获取区域列表：%s", err.Error()), "")
		}
		for j, city := range cityList {
			districtList := make([]models.Region, 0)
			err = db.Where("parent_id = ?", city.Id).Find(&districtList)
			if err != nil {
				return utils.CommonRes(1000, fmt.Sprintf("无法获取区域列表：%s", err.Error()), "")
			}
			cityList[j].Children = districtList
		}
		provinceList[i].Children = cityList
	}

	return utils.CommonRes(20000, "成功获取区域列表", provinceList)
}

//找回密码
func (c *NoLogin) PostFind() interface{} {
	channel := c.Ctx.PostValue("channel")
	phone := c.Ctx.PostValue("phone")
	newPassword := c.Ctx.PostValue("password")
	verifyCode := c.Ctx.PostValue("verifyCode")

	if channel == "" || phone == "" || newPassword == "" || verifyCode == "" {
		return utils.CommonRes(1000, fmt.Sprintf("参数有误"), "")
	}

	//验证手机号
	if !utils.IsMobile(phone) {
		return utils.CommonRes(1000, "请输入正确的手机号", "")
	}

	//校验验证码
	verify := utils.NewVerifyCode(phone, verifyCode)
	ok, msg := verify.Check()
	if !ok {
		return utils.CommonRes(1000, msg, "")
	}

	//连接数据库
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	//更新密码
	newPsw := map[string]interface{}{
		"password": newPassword,
	}

	_, err = db.Table(new(models.User)).Where("phone = ?", phone).Update(newPsw)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("找回密码出错: %s", err), "")
	}

	userInfo := new(models.User)

	_, err = db.Table(new(models.User)).Where("phone = ?", phone).Get(userInfo)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("获取人员信息出错"), "")
	}

	//获取用户账号和密码
	name := userInfo.Name
	psw := userInfo.Password
	userId := userInfo.Id

	userID := strconv.FormatInt(userId, 10)

	//生成token
	token, err := utils.GenerateToken(name, psw, userID)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("创建token出错"), "")
	}

	return utils.CommonRes(1000, fmt.Sprintf("找回密码成功"), token)
}

// 根据城市id获取对应高中列表
func (c *NoLogin) PostHighschool() interface{} {
	cityId := c.Ctx.PostValueDefault("cityId", "")

	if len(cityId) <= 0 {
		return utils.CommonRes(1000, "请选择市", "")
	}

	var err error
	var db *xorm.Engine

	db, err = datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	highSchoolList := make([]models.HighSchool, 0)
	err = db.Where("city_id = ?", cityId).Find(&highSchoolList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取高中列表：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "成功获取高中列表", highSchoolList)
}

// 根据高中id获取对应班级列表
func (c *NoLogin) PostHighschoolclass() interface{} {
	highSchoolId := c.Ctx.PostValueDefault("highSchoolId", "")

	if len(highSchoolId) <= 0 {
		return utils.CommonRes(1000, "请选择高中", "")
	}

	var err error
	var db *xorm.Engine

	db, err = datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	highSchoolClassList := make([]models.HighSchoolClass, 0)
	err = db.Where("high_school_id = ?", highSchoolId).Find(&highSchoolClassList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取高中班级列表：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "成功获取高中班级列表", highSchoolClassList)
}

func (c *NoLogin) GetUniversity() mvc.Result {
	id := c.Ctx.URLParam("id")

	if len(id) <= 0 {
		return nil
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return nil
	}

	university := new(models.University)
	db.ID(id).Get(university)
	university.CreatedShow = university.Created.Format("2006-01-02")

	universityLabelList := make([]models.UniversityLabelObj, 0)
	db.Table("university_label").Alias("ul").
		Join("LEFT", []string{"label", "l"}, "ul.label_id = l.id").
		Where("ul.university_id = ?", university.Id).Find(&universityLabelList)
	university.LabelList = universityLabelList

	return mvc.View{
		Name: "university_detail.html",
		Data: iris.Map{
			"Info":    university,
			"Content": template.HTML(university.Introduction),
		},
	}
}

func (c *NoLogin) GetProfile() mvc.Result {
	id := c.Ctx.URLParam("id")

	if len(id) <= 0 {
		return nil
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return nil
	}

	enrollProfile := new(models.EnrollProfile)
	db.ID(id).Get(enrollProfile)

	return mvc.View{
		Name: "university_profile.html",
		Data: iris.Map{
			"Content": template.HTML(enrollProfile.Content),
		},
	}
}
